import { Provide, Inject } from '@midwayjs/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository } from 'typeorm';
import { TaskResult } from '../entity/taskResults.entity'; // 导入 TaskResult 实体
import { TaskResultCreateDto, TaskResultUpdateDto, TaskResultQueryDto, TaskResultDeleteDto } from '../dto/taskResult.dto'; // 导入 DTO

@Provide()
export class TaskResultService {
  @InjectEntityModel(TaskResult)
  private readonly taskResultRepository: Repository<TaskResult>; // 注入 TaskResult 的 Repository

  /**
   * 创建任务成果
   * @param createDto 创建任务成果的数据传输对象
   * @returns 创建的任务成果
   */
  async createTaskResult(createDto: TaskResultCreateDto): Promise<TaskResult> {
    const taskResult = new TaskResult();
    
    taskResult.resultName = createDto.resultName;
    taskResult.resultDescription = createDto.resultDescription;
    taskResult.completionDate = createDto.completionDate;
    taskResult.isCompleted = createDto.isCompleted;
    taskResult.detectionTime = createDto.detectionTime;
    taskResult.taskType = createDto.taskType;
    taskResult.taskSource = createDto.taskSource;
    taskResult.vectorFileAddress = createDto.vectorFileAddress;

    return await this.taskResultRepository.save(taskResult);
  }

  /**
   * 更新任务成果
   * @param updateDto 更新任务成果的数据传输对象
   * @returns 更新后的任务成果
   */
  async updateTaskResult(updateDto: TaskResultUpdateDto): Promise<TaskResult> {
    const taskResult = await this.taskResultRepository.findOne({ 
      where: { id: updateDto.id } 
    });

    if (!taskResult) {
      throw new Error('Task result not found');
    }

    // 只更新传入的字段
    if (updateDto.resultName !== undefined) {
      taskResult.resultName = updateDto.resultName;
    }
    if (updateDto.resultDescription !== undefined) {
      taskResult.resultDescription = updateDto.resultDescription;
    }
    if (updateDto.completionDate !== undefined) {
      taskResult.completionDate = updateDto.completionDate;
    }
    if (updateDto.isCompleted !== undefined) {
      taskResult.isCompleted = updateDto.isCompleted;
    }
    if (updateDto.detectionTime !== undefined) {
      taskResult.detectionTime = updateDto.detectionTime;
    }
    if (updateDto.taskType !== undefined) {
      taskResult.taskType = updateDto.taskType;
    }
    if (updateDto.taskSource !== undefined) {
      taskResult.taskSource = updateDto.taskSource;
    }
    if (updateDto.vectorFileAddress !== undefined) {
      taskResult.vectorFileAddress = updateDto.vectorFileAddress;
    }

    return await this.taskResultRepository.save(taskResult);
  }

  /**
   * 删除任务成果
   * @param deleteDto 删除任务成果的数据传输对象
   * @returns 删除结果
   */
  async deleteTaskResult(deleteDto: TaskResultDeleteDto): Promise<boolean> {
    const result = await this.taskResultRepository.delete(deleteDto.id);
    return result.affected > 0;
  }

  /**
   * 根据ID查询任务成果
   * @param id 任务成果ID
   * @returns 查询到的任务成果
   */
  async getTaskResultById(id: string): Promise<TaskResult | null> {
    return await this.taskResultRepository.findOne({ 
      where: { id } 
    });
  }

  /**
   * 分页查询任务成果
   * @param queryDto 查询参数
   * @returns 查询结果和总数
   */
  async queryTaskResults(queryDto: TaskResultQueryDto): Promise<{ 
    list: TaskResult[], 
    total: number 
  }> {
    const { 
      resultName, 
      isCompleted, 
      detectionTime, 
      taskType, 
      taskSource, 
      page, 
      limit 
    } = queryDto;

    const queryBuilder = this.taskResultRepository
      .createQueryBuilder('taskResults')
      .select();

    // 动态添加查询条件
    if (resultName) {
      queryBuilder.andWhere('taskResults.resultName LIKE :resultName', { 
        resultName: `%${resultName}%` 
      });
    }
    if (isCompleted !== undefined) {
      queryBuilder.andWhere('taskResults.isCompleted = :isCompleted', { isCompleted });
    }
    if (detectionTime) {
      queryBuilder.andWhere('taskResults.detectionTime = :detectionTime', { detectionTime });
    }
    if (taskType) {
      queryBuilder.andWhere('taskResults.taskType = :taskType', { taskType });
    }
    if (taskSource) {
      queryBuilder.andWhere('taskResults.taskSource = :taskSource', { taskSource });
    }

    // 分页
    queryBuilder
      .skip((page - 1) * limit)
      .take(limit)
      .orderBy('taskResults.creationTime', 'DESC');

    const [list, total] = await queryBuilder.getManyAndCount();

    return { 
      list, 
      total 
    };
  }
}